<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>云备份文件下载</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            box-sizing: border-box;
            font-family: "PingFang SC";
            background-color: white;
        }

        nav {
            background-color: #f9f9f9;
            padding: 20px 0;
            text-align: center;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
        }

        nav a {
            text-decoration: none;
            color: #333;
            margin: 0 15px;
            font-weight: bold;
            transition: color 0.3s ease-in-out;
        }

        nav a:hover {
            color: #555;
        }


        header h1 {
            margin: 20px 0;
            text-align: center;
            color: #333;

            font-size: 2em;
            margin-bottom: 40px;
        }

        .search {
            display: flex;
            justify-content: center;
            margin: 20px auto 20px;
            width: 80%;
            max-width: 600px;
        }

        .search input[type=text] {
            padding: 8px;
            margin-right: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        .search button {
            padding: 10px 20px;
            color: #f5f5f5;
            background-color: #333;
            border: none;
            cursor: pointer;
            border-radius: 5px;
            font-weight: bold;
        }

        .search button:hover {
            background-color: #555;
            color: #fff;
        }

        table {
            width: 70%;
            margin: 50px auto;
            border-collapse: collapse;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            border-radius: 8px;
            overflow: hidden;
        }

        table,
        th,
        td {
            border: 1px solid #ccc;
        }

        th,
        td {
            padding: 10px;
            text-align: center;
        }

        th {
            padding: 12px;
            background-color: #f8f8f8;
        }

        table td a {
            color: #333;
            text-decoration: none;
            transition: color 0.3s ease-in-out;
        }

        table td a:hover {
            color: #555;
            text-decoration: underline;
        }

        footer {
            color: #333;
            background-color: #f9f9f9;
            text-align: center;
            padding: 20px;
            margin-top: 100px;
        }

        /* 弹窗基本样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
            padding-top: 100px;
        }

        .modal-content {
            background-color: #f9f9f9;
            margin: auto;
            padding: 20px;
            border: 1px solid #ccc;
            width: 80%;
            max-width: 500px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
        }
    </style>
</head>

<body>
    <nav>
        <a href="/">首页</a>
        <a href="/upload.html">上传</a>
        <a href="#" id="search_link">搜索</a>
        <a href="#">登录</a>
        <a href="#">竞赛</a>
        <a href="#">讨论</a>
        <a href="#">求职</a>
    </nav>

    <header>
        <h1>欢迎下载云备份文件</h1>
    </header>

    <div class="search">
        <input type="text" id="search_input" placeholder="搜索...">
        <button id="search_button">搜索一下</button>
    </div>

    <div id="error_modal" class="modal">
        <div class="modal-content">
            <p id="error_msg"></p>
        </div>
    </div>

    <div class="file_list">
        <table>
            <thead>
                <tr>
                    <th style="width: 45%;" class="file_col">file link</th>
                    <th style="width: 35%;" class="time_col">last modify time</th>
                    <th style="width: auto;" class="size_col">file size</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>

    <footer>
        <p>@yourfriendyo</p>
    </footer>
</body>

<script>
    // 当文档加载完成后执行fetachRecords
    document.addEventListener('DOMContentLoaded', function() {
        fetchAndShowRecords('/record');
        setSearchButton();
        setSearchInput();
    });

    function fetchAndShowRecords(url) {
        fetch(url)
            .then(response => response.json()) // 将响应数据转换为JSON
            .then(data => {
                if (data && Array.isArray(data)) {
                    updateTable(data); // 更新表格内容
                }
            })
            .catch(error => {
                showError('Error fetching records: ' + error.message);
            });
    }

    function updateTable(records) {
        const tableBody = document.querySelector('.file_list table tbody');
        // 清空表格
        tableBody.innerHTML = '';
        // 遍历记录，添加到表格中
        records.forEach(record => {
            const row = document.createElement('tr');
            row.innerHTML = `<td class="fpath"><a href="${record.dlurl}">${record.fpath}</a></td>
                             <td class="ftime">${formatDate(record.mtime * 1000)}</td>
                             <td class="fsize">${formatSize(record.fsize)}</td>`;
            tableBody.appendChild(row); // 将新行添加到表格
        });
    }

    function formatDate(time) {
        const date = new Date(time);
        const year = date.getFullYear();
        // 月份从0开始，因此加1。使用padStart保证至少两位数。
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        // 使用padStart保证日期为两位数。
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    function formatSize(bytes) {
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        if (bytes == 0) return '0 Byte';
        const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
        if (i == 0) return bytes + ' ' + sizes[i];
        return (bytes / Math.pow(1024, i)).toFixed(2) + ' ' + sizes[i];
    }

    function search() {
        var text = document.getElementById('search_input').value
        var url = '/search/' + encodeURIComponent(text);
        if (text.trim()) {
            fetchAndShowRecords(url);
        }
    }

    function setSearchButton() {
        // 首先，查找到我们刚刚设置id的搜索链接和搜索输入框
        const searchLink = document.getElementById('search_link');
        const searchInput = document.querySelector('.search input');

        // 给搜索链接添加点击事件监听
        searchLink.addEventListener('click', function(event) {
            event.preventDefault(); // 防止<a>标签的默认页面跳转行为
            searchInput.focus(); // 将焦点设置到搜索输入框
        });

        // 给搜索按钮绑定点击事件
        document.getElementById('search_button').addEventListener('click', search);
    }

    function setSearchInput() {
        document.getElementById('search_input').addEventListener('keydown', function(event) {
            if (event.key === "Enter") {
                event.preventDefault(); // 阻止Enter键的默认行为（如提交表单）
                search();
            }
        });
    }

    function showError(message) {
        const modal = document.getElementById('error_modal');
        const errorMessage = document.getElementById('error_msg');
        errorMessage.textContent = message; // 按需设置错误信息
        modal.style.display = "block"; // 显示弹窗

        // 点击窗口外部隐藏弹窗
        window.onclick = function (event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }
        }
    }
</script>

</html>
